<template>
  <div class="Roombox">
    <!-- 顶部S -->
    <div class="RoomTop">
      <van-nav-bar>
        <template #right>
          <van-icon name="location-o" size="25" color="#fff" @click="$router.push('/map')"/>
        </template>
        <template #left>
          <van-icon
            name="arrow-left"
            size="25"
            color="#fff"
            @click="$router.go(-1)"
          />
        </template>
      </van-nav-bar>
    </div>
    <!-- 顶部E -->
    <!-- 搜索框S -->
    <div class="RoomTopsearch">
      <van-search
        v-model="value"
        placeholder="| 请输入搜索关键词"
        background="#0000"
        left-icon="arrow-down"
      >
        <template #label>
          <div @click="onCity">{{NowCity}}</div>
        </template>
      </van-search>
    </div>
    <!-- 搜索框E -->
    <!-- 下拉菜单S -->
    <div class="DownMenu">
      <!-- 下拉菜单大盒子 -->
      <van-dropdown-menu active-color="#21b97a">
        <!-- 下拉菜单每一项 -->
        <van-dropdown-item
          lazy-render
          :title="DownMenuItem.text"
          @open="DropDownBtn(DownMenuItem)"
          v-for="(DownMenuItem, DownMenuIndex) in DownMenuList"
          :key="DownMenuIndex"
        >
          <!-- 侧边弹出层 -->
          <div class="PopUpBox">
            <van-popup
              v-model="show"
              get-container="body"
              position="right"
              :style="{ height: '100%', width: '80%' }"
              :overlay-style="{ backgroundColor: 'rgb(0, 0, 0,0.3)' }"
            >
              <!-- 弹出层内容 -->
              <div
                class="PopUpContent"
                v-for="(DataItem, DataIndex) in newData"
                :key="DataIndex"
              >
                <van-grid column-num="2" gutter="10">
                  <!-- 名称（户型，楼层...） -->
                  <van-cell :title="DataIndex" :border="false" />
                  <!-- 内容 -->
                  <van-grid-item
                    v-for="(newItem, newIndex) in DataItem"
                    :key="newIndex"
                  >
                    <div
                      @click="
                        PopAddClassbtn(DataItem, DataIndex, newIndex, $event)
                      "
                    >
                      {{ newItem.label }}
                    </div>
                  </van-grid-item>
                </van-grid>
                <!-- 分隔线 -->
                <van-divider
                  :style="{
                    color: '#999',
                    borderColor: '#999',
                    padding: '0 16px',
                  }"
                />
              </div>
              <!-- 弹出层底部按钮 -->
              <div class="PopBtn">
                <van-button type="default" @click="PopRemoveBtn"
                  >清除</van-button
                >
                <van-button type="primary" @click="PopConfirmBtn"
                  >确定</van-button
                >
              </div>
            </van-popup>
          </div>
          <!-- picker选择器 -->
          <!-- 三元判断显示那块列表内容 -->
          <van-picker
            show-toolbar
            v-model="value1"
            v-show="showlist < 4"
            :columns="
              showlist > 1 ? (showlist > 2 ? Moneylist : Rentallist) : columns
            "
            @change="onChange"
            @confirm="onconfirm"
          />
        </van-dropdown-item>
      </van-dropdown-menu>
    </div>
    <!-- 下拉菜单E -->
    <!-- 房屋信息列表 -->
    <div>
      <!-- 下拉刷新 -->
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="ListLoading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        offset="50"
        :immediate-check="false"
        direction="down"
      >
        <van-card
          :price="`${HouseItem.price}元/月`"
          :desc="HouseItem.desc"
          :title="HouseItem.title"
          class="goods-card"
          centered
          currency
          :thumb="`http://liufusong.top:8080${HouseItem.houseImg}`"
          v-for="(HouseItem, HouseIndex) in HouseList"
          :key="HouseIndex"
          @click="Houses(HouseItem)"
        >
          <template #tags>
            <van-tag
              color="#e1f5f8"
              text-color="#39becd"
              v-for="(tagsItem, tagsIndex) in HouseItem.tags"
              :key="tagsIndex"
            >
              {{ tagsItem }}</van-tag
            >
          </template>
        </van-card>
      </van-list>
    </van-pull-refresh>
    </div>
  </div>
</template>

<script>
import { RegionRequest, SublevelRequest, HouseReleaseRequest, HouseRequest } from '@/api'
import { mapState } from 'vuex'
export default {
  name: 'FindRoom',
  data () {
    return {
      // 搜索输入框
      value: '',
      // VanPicker绑定value
      value1: '',
      // 判断下拉菜单展示那个菜单页
      showlist: 1,
      // 一级城市详细数据
      bodylist: [],
      // 二级城市
      twolist: [],
      // 房屋筛选
      HouseScreen: [],
      // 房屋信息
      HouseList: [],
      // 侧边弹出框
      show: false,
      // 下拉刷新
      ListLoading: false,
      finished: false,
      refreshing: false,
      // 弹出层内容
      newData: {},
      NowCity: null
    }
  },
  async activated () {
    this.NowCity = this.$store.state.NowCityOlny[0].label || '杭州'
    // 判断登录状态
    this.$store.dispatch('UserRes')
    this.RoomScreenObj.NewHouse = this.$store.state.NowCityOlny[0].value
    this.GetOneCityReg()
    this.House()
    this.HouseRelease()
  },
  methods: {
    // 1级城市数据
    async GetOneCityReg () {
      // 请求1级城市数据
      const res = await RegionRequest(this.$store.state.NowCityOlny[0].value || this.$store.state.NowCityOlny)
      console.log(this.$store.state.NowCityOlny)
      // 解构需要的数据
      const { data: { body } } = res
      // 取出每项label（城市名）放入渲染数组
      this.columns[1].values = body.map(item => { return item.label })
      // 将得到的数据赋值给空对象，城市ID用于获取2级城市列表
      this.bodylist = body
    },
    // 下拉菜单滚动获取，事件（区域项）
    async onChange (picker, value, index) {
      // 获取2级城市
      // 如果index为1，说明是中间列动了，渲染下级城市
      if (index === 1) {
        // 2级城市请求接口，参数为1级城市ID
        const res = await SublevelRequest(this.bodylist[picker.getColumnIndex(index)].value)
        const { data: { body } } = res
        // 获得2级城市详细数据
        this.twolist = body
        // 每次触发先清空2级城市渲染列表
        this.columns[2].values = []
        // list得到2级城市名，再展开拼接'不限'
        const list = body.map(item => { return item.label })
        this.columns[2].values = ['不限', ...list]
        // 获取1级城市ID，用于筛选房屋参数
        this.RoomScreenObj.NewHouse = this.bodylist[picker.getColumnIndex(index)].value
      }
      if (index === 2) {
        // 如果滚动的是2级城市(index为2的)获取2级城市ID，筛选房屋参数
        this.RoomScreenObj.NewHouse = this.twolist[picker.getColumnIndex(index) - 1].value
      }
      // 判断合租整租（方式项）
      // value值为当前滚动项，判断条件，赋值
      if (value[0] === '整租') {
        this.RoomScreenObj.RentalMode = true
      } else if (value[0] === '合租') {
        this.RoomScreenObj.RentalMode = false
      } else {
        this.RoomScreenObj.RentalMode = null
      }
      // 点击的下拉配置项索引是否为3（租金项）
      if (this.showlist === 3) {
        // 下标找出当前点击的金额是那个
        this.RoomScreenObj.Money = this.Moneylist[0].values[picker.getColumnIndex(index)]
        // 后端接收的数据为整数，需要通过截取字符串拿出大整数
        this.RoomScreenObj.Money = this.RoomScreenObj.Money.slice(5, 9)
      }
    },
    // 点击下拉菜单操作
    DropDownBtn (item) {
      if (item.id === 1) {
        this.showlist = 1
      }
      if (item.id === 2) {
        this.showlist = 2
      }
      if (item.id === 3) {
        this.showlist = 3
      }
      if (item.id === 4) {
        this.showlist = 4
        this.show = true
      }
    },
    // 下拉菜单确定按钮
    onconfirm (value, index) {
      // 固定下拉菜单滚动位置
      this.columns[1].defaultIndex = index[1]
      this.columns[2].defaultIndex = index[2]
      // 确定后携带参数发送请求
      this.House(this.RoomScreenObj)
    },
    // 房屋筛选，展示信息
    // 筛选的数据全部打包在RoomScreenObj，通过对象解构方式
    async House (RoomScreenObj) {
      this.$store.state.UserOverlay = true
      // 加载状态
      this.$bus.$emit('loading')
      try {
        // 房屋信息请求
        const res = await HouseRequest(RoomScreenObj || this.RoomScreenObj)
        this.HouseList = res.data.body.list
        this.$store.state.UserOverlay = false
        // 加载完毕关闭加载窗
        this.$bus.$emit('clear')
      } catch (err) {
        this.$bus.$emit('fail')
        this.$store.state.UserOverlay = false
      }
    },
    // 房间筛选弹窗
    async HouseRelease () {
      // 获取筛选条件
      const res = await HouseReleaseRequest()
      this.HouseScreen = res.data.body
      // 数据调整S
      this.HouseScreen = JSON.parse(JSON.stringify(this.HouseScreen).replace(/"floor"/g, '"楼层"').replace(/"supporting"/g, '"房屋亮点"').replace(/"oriented"/g, '"朝向"').replace(/"roomType"/g, '"户型"'))
      const data = {}
      Object.keys(this.HouseScreen).reverse().forEach((item) => {
        if (item.length <= 2) {
          this.newData[item] = this.HouseScreen[item]
        }
        if (item.length > 2) {
          // eslint-disable-next-line no-const-assign
          data[item] = this.HouseScreen[item]
        }
      })
      this.newData = { ...this.newData, ...data }
      // 数据调整E
    },
    // 无限刷新
    async onLoad () {
      this.$store.state.UserOverlay = true
      this.ListLoading = true
      this.$store.state.RoomScreenObj.end += 10
      // 加载状态
      this.$bus.$emit('loading')
      try {
        const res = await HouseRequest(this.RoomScreenObj)
        this.HouseList = [...res.data.body.list]
        if (res.data.body.list.length === 0) {
          this.finished = true
        }
        this.refreshing = false
        this.ListLoading = false
        // 加载完毕关闭加载窗
        this.$store.state.UserOverlay = false
        this.$bus.$emit('clear')
      } catch (err) {
        console.log(err)
        this.$bus.$emit('fail')
        this.$store.state.UserOverlay = false
      }
    },
    onRefresh () {
      this.finished = false
      this.$store.state.RoomScreenObj.end = Math.floor(Math.random() * 50)
      this.$store.state.RoomScreenObj.start = Math.floor(Math.random() * this.$store.state.RoomScreenObj.end)
      console.log(this.$store.state.RoomScreenObj.start = Math.floor(Math.random() * this.$store.state.RoomScreenObj.end))
      this.onLoad()
    },
    // 跳转城市列表页面
    onCity () {
      this.$router.push({
        path: '/city'
      })
    },
    // 跳转房屋详细信息页面
    Houses (item) {
      this.$router.push({
        name: 'detail'
      })
      this.$store.commit('houseId', item.houseCode)
      console.log(item)
    },
    // 筛选，弹出层内容
    PopAddClassbtn (DataItem, DataIndex, newIndex, e) {
      // 添加类名
      e.target.classList.toggle('active')
      // 数据整合
      if (DataIndex === '户型') {
        this.RoomScreenObj.roomType = DataItem[newIndex].value
      } else if (DataIndex === '朝向') {
        this.RoomScreenObj.oriented = DataItem[newIndex].value
      } else if (DataIndex === '楼层') {
        this.RoomScreenObj.floor = DataItem[newIndex].value
      }
    },
    PopConfirmBtn () {
      this.show = false
      // 确定按钮发送请求
      this.House(this.RoomScreenObj)
    },
    PopRemoveBtn (e) {
      // 清除类名，清除对应数据
      Array.from(document.getElementsByClassName('active')).forEach(item => {
        item.className = ''
      })
      this.RoomScreenObj.roomType = null
      this.RoomScreenObj.oriented = null
      this.RoomScreenObj.floor = null
    }
  },
  computed: {
    // 使用vuex辅助函数
    ...mapState(['DownMenuList', 'Rentallist', 'Moneylist', 'columns', 'RoomScreenObj', 'houseCode'])
  }
}
</script>

<style lang="less" scoped>
.Roombox {
  //  顶部背景色，定位
  .RoomTop {
    /deep/ .van-nav-bar__content {
      background-color: #21b97a;
    }
    /deep/ .van-icon-arrow-left {
      color: #fff;
      font-size: 20px;
      margin:0 -10px;
    }
  }
  // 顶部搜索
  .RoomTopsearch {
    position: absolute;
    top: 0;
    left: 30px;
    width: 80%;
    height: 40px;
    margin-top: -4px;
    z-index: 999;
  }
}
.van-picker {
  position: relative;
  /deep/ .van-picker__toolbar {
    position: absolute;
    display: flex;
    border-top: 1px solid rgb(185, 183, 183);
    bottom: 0;
    width: 100%;
    z-index: 999;
    .van-picker__confirm {
      flex: 2;
      background-color: #21b97a;
      color: #fff;
      font-size: 18px;
    }
    .van-picker__cancel {
      flex: 1;
      color: #21b97a;
      font-size: 18px;
    }
  }
}
/deep/ .van-card__price-integer {
  color: red;
  font-weight: 700;
}
/deep/ .van-tag {
  margin: 0 3px;
}
.PopUpBox {
  text-align: center;
}
/deep/ .van-grid-item__content {
  height: 32px;
  width: 70px;
  margin: 0 30px;
  border: 1px solid #ddd;
  border-radius: 3px;
  text-align: center;
  font-size: 12px;
  color: #888;
}
/deep/ .van-grid-item {
  margin-left: 20px;
  width: 80px;
  flex-basis: 0% !important;
}
.active {
  width: 105%;
  padding: 7px;
  border: 1px solid #21b97a;
  color: #21b97a;
  background-color: #defaef;
}
.PopBtn {
  display: flex;
  margin-top: -17px;
  /deep/ .van-button {
    height: 50px;
    color: #21b97a;
    flex: 0.5;
    font-size: 18px;
  }
  /deep/ .van-button--primary {
    flex: 1;
    color: #fff;
    background-color: #21b97a;
  }
}
</style>
